package com.project.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.project.bean.UserBean;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.time.LocalDate;

//标识该类为应用控制器类
@Controller
@RequestMapping("user")
public class TestController {

    //标识该方法的请求URL路径
    @RequestMapping("test")
    public String test(){
        System.out.println("访问test");

        //重定向到指定页面
        return "redirect:/html/index.html";
    }

    @RequestMapping("add")
    public String add(UserBean user,String name, int money) throws IOException {
        System.out.println(user+"  "+name+"  "+money);
        return "redirect:/html/index.html";
    }

    @RequestMapping("speak")
    public void speak(HttpServletRequest req,HttpServletResponse rp) throws IOException {
        rp.setContentType("text/html; Charset=utf-8");
        rp.getWriter().println("hello，美女");
    }

    @RequestMapping("/testUrl/{aaa}")
    public void testUrl(@PathVariable("aaa") int id){
        System.out.println(id);
    }

    @RequestMapping("/cut")
    public void cut(@RequestParam(value = "pg",defaultValue = "1") int pageNO){
        System.out.println("pageNO="+pageNO);
    }

    @RequestMapping("/getObj")
    public void getObj(HttpServletResponse response) throws Exception {
        response.setContentType("text/html;charset=utf-8");
        UserBean user = new UserBean("小刘","222",10000, LocalDate.parse("1998-09-09"));
        ObjectMapper om = new ObjectMapper();
        om.registerModule(new JavaTimeModule());
        String str = om.writeValueAsString(user);
        response.getWriter().println(str);
//        OutputStream out = response.getOutputStream();
    }

    @RequestMapping("/getUser")
    @ResponseBody
    public UserBean getUser() throws Exception {
        UserBean user = new UserBean("小刘","222",10000, LocalDate.parse("1998-09-09"));
        return user;
    }
}
